//
//  StatusCell.swift
//  CXCWeibo
//
//  Created by cxc on 15/7/1.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit
import SDWebImage
import FFAutoLayout

protocol StatusCellDelegate:NSObjectProtocol {
    func statusCellDidSelectedPhoto(cell:StatusCell,photoIndex:Int)
}

 /// 图片视图可从用表示符
private let CCPictureCellReuseIdentifier = "CCPictureCellReuseIdentifier"
 /// 带转发cell的重用ID
let CCStatusForwardCellReuseIdentifier = "CCStatusForwardCellReuseIdentifier"
/// 原创微博的cell
let CCStatusNormalCellReuserIdentifier = "CCStatusNormalCellReuserIdentifier"

class StatusCell: UITableViewCell ,UICollectionViewDataSource,UICollectionViewDelegate {
    
    weak var photoDelegate:StatusCellDelegate?
    
    var widthCons:NSLayoutConstraint?
    var heightCons:NSLayoutConstraint?
    var topCons:NSLayoutConstraint?
    
    var forwardLabel:UILabel?
    
    var status:Status?{
        didSet{
            forwardLabel?.text = (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")
            
            iconView.sd_setImageWithURL(status?.user?.profileURL)
            memberIconView.image = status?.user?.mbImage
            vipIconView.image = status?.user?.verifiedImage
            
            nameLaber.text = status?.user?.name
            timeLaber.text = "刚刚"
            sourceLaber.text = "来自 微博"
            contentLaber.text = status?.text
            
            // 计算图片视图的大小
            let result = calcPictureViewSize(status!)
            
            topCons?.constant = result.0.height == 0 ? 0 : 12
            widthCons?.constant = result.0.width
            heightCons?.constant = result.0.height
            pictureLayout.itemSize = result.1
            
            pictureView.reloadData()
        }
    }
    func fullScreenFrame(photoIndex:Int) -> CGRect{
        let urlString = status!.picURLs![photoIndex].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
        
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        let w = screenSize.width
        let h = w * scale
        var y: CGFloat = 0
        if h < screenSize.height {
            y = (screenSize.height - h) * 0.5
        }
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    
    func screenFrame(photoIndex:Int) -> CGRect{
        let indexPath = NSIndexPath(forItem: photoIndex, inSection: 0)
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! StatusPictureCell
        return pictureView.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    class func cellReuseIdentifier(status:Status) -> String {
        return status.retweeted_status != nil ? CCStatusForwardCellReuseIdentifier : CCStatusNormalCellReuserIdentifier
    }
    func rowHeight(status:Status) -> CGFloat{
        self.status = status
        layoutIfNeeded()
        
        return CGRectGetMaxY(footerView.frame)
    }
    // MARK: - 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.imageURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CCPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        
        cell.imageURL = status!.imageURLs![indexPath.item]
        
        return cell
    }
    // MARK: - CollectionViewDelegate
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let url = status?.largePicURLs![indexPath.item]
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! StatusPictureCell
        
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (bytes, totalBytes) -> Void in
            let progress = CGFloat(bytes) / CGFloat(totalBytes)
            dispatch_async(dispatch_get_main_queue()) {
                cell.iconView.progress = progress
            }
            }) { [unowned self] (_,error,_,_,_) -> Void in
              self.photoDelegate?.statusCellDidSelectedPhoto(self, photoIndex: indexPath.item)
        }
        
    }
    
    
    private func calcPictureViewSize(status:Status) -> (viewSize:CGSize,itemSize:CGSize){
        let itemSize:CGSize = CGSize(width: 90, height: 90)
        let margin:CGFloat = 10
        
        let count = status.imageURLs?.count ?? 0
        if count == 0{
            return (CGSizeZero,itemSize)
        }
        if count == 1{
            let key = status.imageURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return(image.size,image.size)
        }
        if count == 4{
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w),itemSize)
        }
        
        let rowCount = 3
        let row = (count - 1)/rowCount+1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount-1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        return (CGSize(width: w, height: h),itemSize)
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let screenWidth = UIScreen.mainScreen().bounds.width
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.6, alpha: 1)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWidth, height: 10))
        
        addSubview(iconView)
        addSubview(nameLaber)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLaber)
        addSubview(sourceLaber)
        addSubview(contentLaber)
        
        contentLaber.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 16
        addSubview(pictureView)
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        //准备配图视图
        preparePictureView()
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 22))
        nameLaber.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLaber, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        
        timeLaber.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLaber.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLaber, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLaber.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))

        //页脚视图
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44), offset: CGPoint(x: -12, y: 12))
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func preparePictureView() {
        pictureView.backgroundColor = UIColor.lightGrayColor()
        pictureView.dataSource = self
        pictureView.delegate = self
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: CCPictureCellReuseIdentifier)
        
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
    }
    func recordPictureViewCons(cons:[NSLayoutConstraint]){
        topCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    // MARK: - 控件的懒加载
    lazy var iconView = UIImageView()
    lazy var nameLaber = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    lazy var vipIconView:UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    lazy var timeLaber = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    lazy var sourceLaber = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    lazy var contentLaber = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)
    
    // 图形视图
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout:self.pictureLayout)
    lazy var footerView: StatusFooterView = StatusFooterView()

}


 /// 配图cell
private class StatusPictureCell:UICollectionViewCell{
    var imageURL:NSURL?{
        didSet{
            iconView.progress = 0
            iconView.sd_setImageWithURL(imageURL)
            
            gifImageView.hidden = !(imageURL!.absoluteString.pathExtension.lowercaseString == "gif")
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        
        addSubview(iconView)
        iconView.ff_Fill(self)
        
        addSubview(gifImageView)
        gifImageView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var iconView:CCImageView = CCImageView()
    private lazy var gifImageView: UIImageView = {
        let giv = UIImageView(image: UIImage(named: "timeline_image_gif"))
        giv.hidden = true
        
        return giv
    }()
}

/// 页脚视图
 class StatusFooterView:UIView{
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        // 水平平铺
        ff_HorizontalTile([forwardBtn,commentBtn,likeBtn], insets: UIEdgeInsetsZero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("转发", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_retweet"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
    }()
    
    lazy var commentBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("评论", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_comment"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
    }()
    
    lazy var likeBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("点赞", forState: UIControlState.Normal)
        btn.setImage(UIImage(named:  "timeline_icon_unlike"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
    }()
}